{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n",
    "                _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n",
    "                                                  sequence_length=X_seq_len,\n",
    "                                                  dtype = tf.float32)\n",
    "                \n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = last_state,\n",
    "                                               dtype = tf.float32)\n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-884f583fbfc1>:11: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-884f583fbfc1>:28: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-884f583fbfc1>:31: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:958: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:962: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From <ipython-input-7-884f583fbfc1>:39: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1, 30208,  9466, 21054, 21054, 11991, 11991, 11991, 22891,\n",
       "          22891, 24164, 24164, 24164, 24164, 20460, 20460,  3993,  3993,\n",
       "           3993,  1103, 27324, 27324, 27324, 27324, 29798, 29798, 29798,\n",
       "          29798, 29798, 24228, 17000, 31763, 17000, 18836, 18836, 27529,\n",
       "          25128]],\n",
       " \n",
       "        [[    1,  7734, 12324, 12324, 15213, 15213, 23375, 23375,  2527,\n",
       "           2527,  2527,  9949,  9721,  9949, 17717, 30276,  3281,  3281,\n",
       "           3281,  3281, 30739, 18470, 18470, 13157, 13157, 19973, 19973,\n",
       "          19973, 15052, 15052, 12855, 12855, 12855,  3296,  3296,  3296,\n",
       "          10728]],\n",
       " \n",
       "        [[    1, 11021, 18548, 18548, 10432, 10432,  6823,  6823, 26107,\n",
       "          26107, 23252, 15178, 23252, 22902, 16291, 16291, 16291, 27699,\n",
       "          10473, 10473, 29507, 29507, 29507, 18835, 18835, 22324, 22947,\n",
       "          22947, 22947, 22947, 20711, 20711, 20711, 20711, 22964, 26134,\n",
       "          26134]],\n",
       " \n",
       "        [[    1, 26091, 13779, 25646, 14902, 13686, 14820, 14820,    15,\n",
       "             15,    15,  2673,  2673, 14368, 14368, 23046, 31252, 31252,\n",
       "          14951, 14951, 22092, 25842,  2491,  2491,  2491,  2491,  2491,\n",
       "           9169,  9169,  9169,  9169,  9169,  8789,  8789,  8789, 24681,\n",
       "          24681]],\n",
       " \n",
       "        [[    1,  1706,  1706, 28228,  8811,  8341, 24990, 24990,  1820,\n",
       "           1820, 17451, 17451, 31676, 31676, 31676,  5158, 17451,  5158,\n",
       "          11627, 11627, 11627, 11627, 12141, 12141,  6660,  6660, 11187,\n",
       "          11187,  4193, 13957, 13957, 18767, 18767, 18767,  6037,  6037,\n",
       "          31524]],\n",
       " \n",
       "        [[    1,  1557,  1557, 21575, 21575, 21575, 21575, 21575, 21575,\n",
       "          21575, 16826, 16826, 12498,  3693, 30178, 30178, 30178, 30178,\n",
       "          17152, 16385, 14577, 16385, 19040, 13078, 20407, 20407, 20407,\n",
       "          13078, 13078, 15969, 15969, 14450,  3015,  3015,  3015, 21675,\n",
       "          21675]],\n",
       " \n",
       "        [[    1, 31527, 31527, 23124, 31573, 31573, 31573, 14700, 14700,\n",
       "          24854, 21518,  3275, 15957, 15957, 11109, 11109, 11109,  1877,\n",
       "          15556,  2863, 26404, 26404, 26404,  7297,  6343,  6343,  6343,\n",
       "            490,    98,   490, 12330,  4901,  4901, 15420, 15420, 13670,\n",
       "          13670]],\n",
       " \n",
       "        [[    1, 23259, 20252,  8506,  7579,  7579, 29914, 29914, 21674,\n",
       "          25842, 18450, 22808, 22808, 22808, 14871, 12946, 12946, 14506,\n",
       "          17944, 17944,  3041, 21006,  9297,  9297,  9297, 19615, 19615,\n",
       "           8856,  6664, 15492, 15492,  7244,  7244,  7244,  7244,  7129,\n",
       "           7129]],\n",
       " \n",
       "        [[    1, 18645, 15910, 19592, 20749, 21493, 21493, 21493,  7087,\n",
       "           7087,  7087,  7087,  7087, 12932, 12932, 12932, 12932, 12932,\n",
       "          12932, 12932, 12932, 12932, 25064, 25064, 25064, 25064, 23969,\n",
       "          23969, 24844, 24844, 16812, 16812, 22829, 22829, 17967, 17967,\n",
       "          17967]],\n",
       " \n",
       "        [[    1, 13741,  8114,  8114,  3362,  3362, 22631, 22631, 22631,\n",
       "          16042, 16042, 16042, 26676, 26676, 26676, 18254, 18254,  1540,\n",
       "           1540,  1540,  1540,  5762,  5762,  5762, 28019,  5762,  5762,\n",
       "           5762,  2367,  2367,  7918,  7918,  7918,  7918, 24939, 25219,\n",
       "          25219]]], dtype=int32), 10.373699, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:15<00:00,  3.59it/s, accuracy=0.112, cost=6.86]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.27it/s, accuracy=0.113, cost=6.68]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 7.336535, training avg acc 0.099140\n",
      "epoch 1, testing avg loss 6.772219, testing avg acc 0.124487\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:35<00:00,  3.43it/s, accuracy=0.14, cost=6.23] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.54it/s, accuracy=0.134, cost=6.16]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 6.465442, training avg acc 0.137407\n",
      "epoch 2, testing avg loss 6.274493, testing avg acc 0.144993\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:15<00:00,  3.59it/s, accuracy=0.149, cost=5.67]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.50it/s, accuracy=0.177, cost=5.94]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 5.971231, training avg acc 0.154757\n",
      "epoch 3, testing avg loss 6.024838, testing avg acc 0.153120\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:14<00:00,  3.60it/s, accuracy=0.179, cost=5.16]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.61it/s, accuracy=0.151, cost=5.88]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 5.590272, training avg acc 0.168196\n",
      "epoch 4, testing avg loss 5.900727, testing avg acc 0.155199\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:14<00:00,  3.60it/s, accuracy=0.199, cost=4.7] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.23it/s, accuracy=0.14, cost=5.89] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 5.270885, training avg acc 0.181316\n",
      "epoch 5, testing avg loss 5.855700, testing avg acc 0.155762\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:33<00:00,  3.44it/s, accuracy=0.229, cost=4.33]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.51it/s, accuracy=0.151, cost=5.89]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 5.010848, training avg acc 0.194421\n",
      "epoch 6, testing avg loss 5.878624, testing avg acc 0.154315\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:06<00:00,  3.66it/s, accuracy=0.25, cost=4.13] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.76it/s, accuracy=0.145, cost=5.99]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 4.825886, training avg acc 0.205270\n",
      "epoch 7, testing avg loss 5.899833, testing avg acc 0.154348\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:08<00:00,  3.64it/s, accuracy=0.284, cost=3.8] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.70it/s, accuracy=0.134, cost=5.94]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 4.650713, training avg acc 0.218053\n",
      "epoch 8, testing avg loss 5.953993, testing avg acc 0.153248\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:07<00:00,  3.65it/s, accuracy=0.309, cost=3.58]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.69it/s, accuracy=0.124, cost=6.09]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 4.486340, training avg acc 0.231720\n",
      "epoch 9, testing avg loss 6.026706, testing avg acc 0.151501\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:06<00:00,  3.66it/s, accuracy=0.353, cost=3.34]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.44it/s, accuracy=0.151, cost=6.14]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 4.348073, training avg acc 0.244312\n",
      "epoch 10, testing avg loss 6.101976, testing avg acc 0.149451\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:06<00:00,  3.66it/s, accuracy=0.372, cost=3.19]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.65it/s, accuracy=0.118, cost=6.24]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 4.218134, training avg acc 0.257371\n",
      "epoch 11, testing avg loss 6.175509, testing avg acc 0.147366\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:31<00:00,  3.46it/s, accuracy=0.385, cost=3.06]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.63it/s, accuracy=0.113, cost=6.27]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 4.093669, training avg acc 0.270882\n",
      "epoch 12, testing avg loss 6.293203, testing avg acc 0.143364\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:35<00:00,  3.43it/s, accuracy=0.412, cost=2.97]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.52it/s, accuracy=0.124, cost=6.35]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 3.986524, training avg acc 0.282892\n",
      "epoch 13, testing avg loss 6.350595, testing avg acc 0.142974\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:12<00:00,  3.61it/s, accuracy=0.451, cost=2.77]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.65it/s, accuracy=0.113, cost=6.34]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 3.895981, training avg acc 0.293344\n",
      "epoch 14, testing avg loss 6.439157, testing avg acc 0.140814\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:13<00:00,  3.61it/s, accuracy=0.459, cost=2.68]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.66it/s, accuracy=0.124, cost=6.5] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 3.809973, training avg acc 0.304010\n",
      "epoch 15, testing avg loss 6.526953, testing avg acc 0.139545\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:12<00:00,  3.61it/s, accuracy=0.484, cost=2.57]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.72it/s, accuracy=0.161, cost=6.51]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 3.726538, training avg acc 0.314713\n",
      "epoch 16, testing avg loss 6.599524, testing avg acc 0.139281\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:12<00:00,  3.61it/s, accuracy=0.505, cost=2.49]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.53it/s, accuracy=0.118, cost=6.58]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 3.646194, training avg acc 0.325352\n",
      "epoch 17, testing avg loss 6.691013, testing avg acc 0.136286\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:12<00:00,  3.61it/s, accuracy=0.536, cost=2.41]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.54it/s, accuracy=0.134, cost=6.69]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 3.572692, training avg acc 0.335092\n",
      "epoch 18, testing avg loss 6.754420, testing avg acc 0.137308\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:13<00:00,  3.61it/s, accuracy=0.521, cost=2.35]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.53it/s, accuracy=0.129, cost=6.81]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 3.504389, training avg acc 0.344738\n",
      "epoch 19, testing avg loss 6.856082, testing avg acc 0.134556\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [07:12<00:00,  3.61it/s, accuracy=0.526, cost=2.29]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  8.60it/s, accuracy=0.124, cost=6.77]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 3.441489, training avg acc 0.353301\n",
      "epoch 20, testing avg loss 6.942565, testing avg acc 0.132951\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [01:58<00:00,  2.95s/it]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.016924812"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tensor2tensor.utils import bleu_hook\n",
    "\n",
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)\n",
    "    \n",
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])\n",
    "    \n",
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
